#include "head.h"

void* thread_main(void* p){
    shared_resource_t* pshared_resource = (shared_resource_t*)p;
    
    puts("子线程创建成功");
    MYSQL* mysql = mysql_init(NULL);
    if(!mysql_real_connect(mysql,LOCAL_HOST,pshared_resource->user,
      pshared_resource->password,pshared_resource->data_base,0,NULL,0))
    {
        printf( "子线程 : %s\n", mysql_error(mysql));
    }
    else{
        puts("数据库连接成功 in thread_main");
    }
    while(1){
        dowork(pshared_resource,mysql);
    }
}

static int command_handler(client_info_t* pclient_info, MYSQL* mysql);

int dowork(shared_resource_t* pshared_resource, MYSQL* mysql){
    // 上锁，读队列，解锁，处理命令
    client_info_t client_info;
    bzero(&client_info,sizeof(client_info));
    pthread_mutex_lock(&(pshared_resource->task_queue_mutex));
    while(pshared_resource->task_queue.size == 0){
        pthread_cond_wait(&(pshared_resource->task_queue_cond),&(pshared_resource->task_queue_mutex));
    }
    de_task_queue(&(pshared_resource->task_queue),&client_info);
    pthread_mutex_unlock(&(pshared_resource->task_queue_mutex));
    command_handler(&client_info, mysql);
    
    return 0;
}

int command_handler(client_info_t* pclient_info, MYSQL* mysql){
    if(strcmp(pclient_info->command,"ls") == 0){
        ls_handler(pclient_info, mysql);
    }
    else if(strcmp(pclient_info->command,"cd") == 0){
        cd_handler(pclient_info, mysql);
    }
    else if(strcmp(pclient_info->command,"pwd") == 0){
        pwd_handler(pclient_info, mysql);
    }
    else if(strcmp(pclient_info->command,"mkdir") == 0){
        mkdir_handler(pclient_info, mysql);
    }
    else if(strcmp(pclient_info->command,"rm") == 0){
        rm_handler(pclient_info, mysql);
    }

    else if(strcmp(pclient_info->command,"puts") == 0){
        puts_handler(pclient_info, mysql);
    }
    else if(strcmp(pclient_info->command,"gets") == 0){
        gets_handler(pclient_info, mysql);
    }

    return 0;
}



